#ifndef Networking_ServerClient_H
#define Networking_ServerClient_H

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <pthread.h>

namespace Networking
{
  class Client
  {
  private:
    char buffer[2048];
    int file_descriptor;
    struct sockaddr_in cli_addr;
  public:
    pthread_t Thread;
    Client()
    {

    }
    
    Client(int fd) : file_descriptor(fd) { }
    
    ~Client()
    {
      printf("Client with file descriptor %i was deleted\n", file_descriptor);
    }

    inline int FileDescriptor() const
    {
      return file_descriptor;
    }
    
    void SetSocketAddress(struct sockaddr_in sd)
    {
      cli_addr = sd;
    }
    
    struct sockaddr_in SocketAddress()
    {
      return cli_addr;
    }
    
    std::string SocketAddressASCII()
    {
      return inet_ntoa(cli_addr.sin_addr);
    }
    
    bool Send(const std::string &msg)
    {
      int WriteResult;
      WriteResult = write(file_descriptor, msg.c_str(), msg.size());
      if (WriteResult < 0)
	return false;
      return true;
    }
    
    bool Read()
    {
      int ReadResult;
      memset(buffer, 0, 2048);
      ReadResult = read(file_descriptor, buffer, 2047);
      if (ReadResult < 0)
      {
	printf("Error while reading from socket with file descriptor %i", file_descriptor);
	return false;
      }
      if (ReadResult == 0)
      {
	printf("Got no response from socket with file descriptor %i", file_descriptor);
	return false;
      }
      printf("Message from %s: %s", SocketAddressASCII().c_str(), buffer);
      Send("I got your message!");
    }
  };
}
#endif